package chuangyi.com.org.ViewModel;

import android.content.Context;

import com.solidfire.gson.internal.LinkedTreeMap;

import java.util.ArrayList;

import chuangyi.com.org.DOMIHome.BR;
import chuangyi.com.org.DOMIHome.LoadingDialog;
import chuangyi.com.org.DOMIHome.R;
import chuangyi.com.org.DOMIHome.Utils.Utils;
import chuangyi.com.org.DOMIHome.Utils.WebApi;
import chuangyi.com.org.DOMIHome.adapter.BindingListItem;
import chuangyi.com.org.DOMIHome.adapter.ListBindingAdapter;
import chuangyi.com.org.DOMIHome.adapter.XListAdapterInterface;
import chuangyi.com.org.DOMIHome.adapter.XListBindingAdapter;

/**
 * Created by zxh on 16/12/14.
 */

public class MyDraftBoxModel extends XListModel {

    public MyDraftBoxModel(Context conetxt) {
        super(conetxt);
        super.getHandler().setTitle("草稿箱");
        getAdapter().setVariableId(BR.commonItem);
    }

    @Override
    public void load(final int page) {
        LoadingDialog.getInstance(getContext()).show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                XListAdapterInterface adapter = getAdapter();
                Context context = getContext();
                ArrayList list = WebApi.myDraftBox(getContext(), page);
                try {
//                    {"articleid":"49","title":"null","systime":"2016\/12\/11 21:03:05"}
                    for (Object item : list) {
                        LinkedTreeMap map = (LinkedTreeMap) item;
                        CommonListItem draftItem = new CommonListItem(context, R.layout.i_draft);
                        draftItem.setSystime(Utils.getDateFromFormat(map.get("systime"), "yyyy/MM/dd HH:mm:ss"));
                        draftItem.setId(Utils.getIntValue(map.get("articleid")));
                        draftItem.setTitle((String) map.get("title"));
                        draftItem.setParent(MyDraftBoxModel.this);
                        draftItem.setType(CommonListItem.TYPE_MY_DRAFT);
                        adapter.add(draftItem);
                    }
                } catch (Exception ex) {
                    showToast("解析数据时发生错误");
                }
                if (list.size() > 0) {
                    setCurrentPage(page);
                }
                notifyDataSetChanged(list);
                LoadingDialog.getInstance(getContext()).dismiss();
            }
        }).start();
    }

    @Override
    public void notifyListChanged(int action, BindingListItem item) {
        if (action == ListBindingAdapter.ACTION_REFRESH) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    MyDraftBoxModel.super.onRefresh();
                }
            });
        }
        super.notifyListChanged(action, item);
    }
}
